/*
 * UCLoginUser.java
 * @author Bian Xiaoguang, Qian Wenshuo
 * Created on 2009-10-17, 19:50:03
 *
 * This use case allows users to log in to the system.
 * Precondition: Get the password and username from user login view.
 * Post-condition: The user can login into the searching ticket view.
 */
package ucm;

import model.UsersModel;
import model.DatabaseModel;
import view.UserLogin;

import javax.swing.*;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;


public class UCUserLogin implements UCController {

    private UsersModel user;

    public UCUserLogin() {
        user = new UsersModel("", "", "", "", "");
    }

    public UCUserLogin(UsersModel user) {
        // System retrieves username and password
        this.user = user;
    }

    public UCUserLogin(UserLogin UserLogin) {
        // System retrieves username and password
        this.user = UserLogin.getUserModel();
    }

    // STEP 1 - User Selects Login
    public boolean run() {
        boolean loggedIn = false;
        // STEP 2 - System retrieves username and password
        // This step is integrated into the constructor or
        // may be specified by using run(UserModel)
        // STEP 3 - System validates the username and password
        if (validUser()) {
            // STEP 4 - System displays main view
            JOptionPane.showMessageDialog(new JFrame(),
                    "Login Successful!",
                    "Success",
                    JOptionPane.INFORMATION_MESSAGE);
            loggedIn = true;
            new UCDispalyShowTicket();

        } else {
            // STEP 2a - System display “invalid user login” message
            JOptionPane.showMessageDialog(new JFrame(),
                    "Invalid Username or Password. Try again.",
                    "Error Message",
                    JOptionPane.ERROR_MESSAGE);
                   new ucm.UCDispalyUserLogin();

        }
        return loggedIn;
    }

    private boolean validUser() {
        boolean correct = false;
        String username = user.getUsername();
        String password = user.getPassword();
        DatabaseModel dbModel = DatabaseModel.getInstance();

        // Check whether we should be using ldap authentication or
        // just regular
        if (dbModel.ldapEnabled()) {
            if (username.equals("") || password.equals("")) {
                correct = false;
               }

            // Else we are just using standard database lookup
        } else {
            Connection con = dbModel.getConnection();
            // Make sure there is a connection
            if (con == null) {
                JOptionPane.showMessageDialog(new JFrame(),
                        "Connection to database failed",
                        "Error Message",
                        JOptionPane.ERROR_MESSAGE);
            } else {
                try {
            Statement stmt = con.createStatement(ResultSet.CONCUR_UPDATABLE,
                    ResultSet.CONCUR_UPDATABLE);
            ResultSet res = stmt.executeQuery("SELECT * FROM users WHERE " +
                    "uname = '" + username + "'");

            correct = res.first() && username.equals(res.getString("uname"))
                    && password.equals(res.getString("upassword"));
            if(correct){
                 System.out.println(res.next());
             int uid = res.getInt("uid");
             stmt.executeQuery("TRUNCATE TABLE tempusers");
             stmt.executeUpdate("INSERT INTO tempusers (`UID`, `UNAME`) VALUES ("+uid+", '"+username+"')");
            }

               } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return correct;
    }
}
